package com.zhenyi.fenda.controller;

import java.util.List;

import org.hashids.Hashids;

import com.cenjiawen.common.IndexController;
import com.fenda.common.model.FdAnswer;
import com.fenda.common.model.FdQuestion;
import com.fenda.common.model.FdUser;
import com.jfinal.aop.Before;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.utils.AuthUtils;
import com.zhenyi.fenda.interceptor.AuthInterceptor;
import com.zhenyi.fenda.interceptor.WXInterceptor;

@Before({ AuthInterceptor.class, WXInterceptor.class })
public class FDController extends IndexController {

	protected final int pageSize = 50;
	protected final Hashids orderHash = new Hashids("fdorder", 2);
	protected final Hashids hashId = new Hashids("fenda", 6);
	protected String APP_ID = PropKit.get("FD_APP_ID", "wx24524e8b092948cf");
	protected final String APP_SECRET = PropKit.get("FD_APP_SECRET", "a37ea37c395dd493257257217b95c2fa");
	protected final String PARTNER_KEY = PropKit.get("FD_PARTNER_KEY", "quickplainquickplainquickplainJW");
	/**
	 * 支付消息提醒
	 */
	protected final int NOTIFICACATION_PAY = 1;
	/**
	 * 咨询消息
	 */
	protected final int NOTIFICACATION_ROOM = 2;
	/**
	 * 问题消息
	 */
	protected final int NOTIFICACATION_QUESTION = 3;

	protected String getBodyParam() {
		String json = HttpKit.readData(getRequest());
		return json;
	}

	protected FdUser getUser() {
		String userId = AuthUtils.getTokenUid(this);
		FdUser user = FdUser.dao.findById(userId);
		return user.userInfo();
	}

	protected void questionInfo() {
		String code = getPara(0);
		Long questionId = hashId.decode(code)[0];
		Kv kv = Kv.by("questionId", questionId);
		SqlPara sqlPara = Db.getSqlPara("FdFindQuestion", kv);
		Record record = Db.findFirst(sqlPara);
		SqlPara sqlParaAnswers = Db.getSqlPara("FdFindQuestionAnswers", questionId);
		List<FdAnswer> items = FdAnswer.dao.find(sqlParaAnswers);
		Long answerId = record.getLong("answerId");
		if (answerId != null) {
			for (FdAnswer answer : items) {
				if (answerId.equals(answer.getId())) {
					answer.setIsAnswer(1);
				}
			}
		}
		record.set("answer", items);
		FdQuestion question = FdQuestion.dao.findById(questionId);
		question.setVisitCount(question.getVisitCount() + 1);
		question.update();
		setInfoItem(record);
		setAttr("answer", items);
		render("/fd/questionInfo.html");
	}
}
